package yxy.game.pm2.module.chibi;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.TypeReference;
import org.joda.time.DateTime;

import org.redisson.api.RMap;
import yxy.cherry.battle.module.Position;
import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.chibidate;
import yxy.cherry.game.base.redis.RedisManager;
import yxy.cherry.game.base.redis.RedisType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.Format.FormatType;
import yxy.game.pm2.bean.currency.Currencies;
import yxy.game.pm2.bean.mq.CCReason;
import yxy.game.pm2.message.BattleMessage;
import yxy.game.pm2.message.ChibiMessage;
import yxy.game.pm2.module.CurrencyHandle;
import yxy.game.pm2.module.battle.*;

import java.util.ArrayList;
import java.util.HashMap;

public class ChibiHandle extends BattleModuleHandle {

    public Result mainUI(String playerCode, ChibiMessage.ChibiMainResponse.Builder response) {
        DateTime now = DateTime.now();
        long endtime = now.withTimeAtStartOfDay().plusDays(1).getMillis();
        int week = now.getDayOfWeek();

        ChibiModule module = ChibiModule.get(playerCode);

        for (ChibiStage stage : module.getStages()) {
            ChibiMessage.ChibiBoss.Builder builder = ChibiMessage.ChibiBoss.newBuilder();
            boolean open = (week == 7 || week == stage.getType());
            if (open) {
                builder.setEndtime(endtime);
                builder.setFinish(stage.getFinish());
            }
            builder.setOpen(open);
            builder.setType(stage.getType());

            response.addBoss(builder);
        }

        response.setTimes(module.remainTimes());
        response.setBuytimes(module.remainBuyTimes());

        return Result.Success;
    }

    // battle===========================================================================

    final public static int battleExpireHour = 1;// 战斗数据过期时间（小时）

    protected String code() {
        return BattleType.CHIBI.name();
    }

    public BattleMessage.BattleResponse battleResponse(ChibiModule module, chibidate _data) throws Exception {
        String playerCode = module.getPlayerCode();
        BattleHandle battleHandle = new BattleHandle();

        BattleModule battleModule = BattleModule.create(playerCode);
        battleModule.setType(BattleType.CHIBI);
        battleModule.setCode(code());

        // 玩家的team
        TeamModule teamA = battleHandle.teamPlayer(playerCode, FormatType.普通);
        battleModule.setTeamA(teamA);

        // 关卡
        TeamModule teamB = teamChibi(_data);
        battleModule.setTeamB(teamB);

        battleModule.setSettlement(SettlementChibi.create(playerCode, _data));

        battleModule.set(battleExpireHour);

        module.setTimes(module.getTimes() + 1);
        module.set();

        return battleHandle.battleResponse(battleModule);
    }

    public BattleMessage.BattleExecuteResponse battleResponseExecute(String playerCode, BattleMessage.BattleExecuteRequest request) throws Exception {
        BattleModule module = BattleModule.get(playerCode, code());
        return new BattleHandle().battleResponseExecute(module, request);
    }

    public TeamModule teamChibi(chibidate _data) {
        TeamModule team = new TeamModule();

        ArrayList<FighterModule> fighterModuleList = getFighterModuleList(_data.getId());
        // 武将
        for (int i = 0; i < _data.getHeroid().length; i++) {
            Position position = Position.forValue(i + 1);
            int heroid = _data.getHeroid()[i];
            if (heroid == -1) continue;
            FighterModule fighterModule = fighterModuleList.get(i);
            team.addfighter(position, fighterModule);
        }
        // 神器
        WeaponModule weapon = WeaponModule.create(_data.getWeapondataid(), _data.getWeaponlv(), 0, 0, _data.getWeaponskilllv());
        team.setWeapon(weapon);

        // 信息
        team.setName(_data.getName());
        team.setHead(_data.getHeadid());
        team.setPower(_data.getDps());

        return team;
    }

    public void finish(String playerCode, int dataId) {
        chibidate data = DataCenter.getData(dataId, chibidate.class);
        if (data == null) {
            return;
        }
        ChibiModule module = ChibiModule.get(playerCode);
        ChibiStage stage = module.stage(data.getType());
        if (stage == null) {
            return;
        }
        if ((stage.getFinish() == 0 && data.getRank() == 1) || stage.getFinish() + 1 == data.getRank()) {
            stage.setFinish(data.getRank());
            module.set();

            // 排行榜
            RankChibi.getRank(playerCode).addAndSet(playerCode, 1);
        }
    }

    public static chibidate data(int id) {
        return DataCenter.getData(id, chibidate.class);

    }

    public Result checkCanBattle(ChibiModule module, chibidate data) {
        if (module.remainTimes() <= 0) {
            return Result.ChibiNoTime;// 没有挑战次数了
        }

        DateTime now = DateTime.now();
        int week = now.getDayOfWeek();
        if (week != 7 && week != data.getType()) {
            return Result.ChibiTimeWrong;// 挑战时间不符
        }

        ChibiStage stage = module.stage(data.getType());
        if (stage == null || stage.getFinish() + 1 != data.getRank()) {
            return Result.ChibiCantChallenge;// 关卡尚不能挑战
        }
        return Result.Success;
    }

    public Result sweep(String playerCode, int id, ChibiMessage.ChibiSweepResponse.Builder response) {
        chibidate data = data(id);
        if (data == null) {
            return Result.ParamError;
        }
        ChibiModule module = ChibiModule.get(playerCode);
        if (module.remainTimes() <= 0) {
            return Result.ChibiNoTime;// 没有挑战次数了
        }
        DateTime now = DateTime.now();
        int week = now.getDayOfWeek();
        if (week != 7 && week != data.getType()) {
            return Result.ChibiTimeWrong;// 挑战时间不符
        }
        ChibiStage stage = module.stage(data.getType());
        if (stage == null || stage.getFinish() < data.getRank()) {
            return Result.ChibiCantChallenge;// 关卡尚不能扫荡
        }
        module.setTimes(module.getTimes() + 1);
        module.set();

        Currencies rewards = new Currencies(Currency.create(data.getRewardtype(), data.getRewardid(), data.getRewardnum()));
        new CurrencyHandle().addCurrency(playerCode, CCReason.火烧赤壁, rewards);

        response.setTimes(module.remainTimes());
        response.addAllRewards(new CurrencyHandle().packItems(rewards));
        return Result.Success;
    }


    //获取内存怪物战力属性
    public ArrayList<FighterModule> getFighterModuleList(int id){
        RMap<String, ArrayList<FighterModule>> rMap = RedisManager.getInstance().getConnection(RedisType.REDIS_DATA).client().getMap("INIT:chibidate");
        JSONArray arrary = (JSONArray) JSONArray.toJSON(rMap.get(String.valueOf(id)));
        ArrayList<FighterModule> fighterModules = JSON.parseObject(arrary.toString(), new TypeReference<ArrayList<FighterModule>>() {
        });
        return fighterModules;
    }

}
